// import wx from "weixin-js-sdk";
import { useStore, useCool } from "/@/cool";
import dayjs from "dayjs"
import { constFilter } from "/@/constant"
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'

/**
 *@description 判断数据类型
 * @param {*} anything 任意数据类型 any
 * @return {string} 返回数据类型有Array,Number,Object,Boolean,String,Undefined,Function,Null
 */
export function getVariableType(anything: any) {
    return Object.prototype.toString.call(anything).slice(8, -1)
}

function formatParams(params: any) {
    let newParams: any = {};
    Object.keys(params).forEach(o => {
        params[o] && (newParams[o] = params[o]);
    })
    return newParams;
}

// 计算价格合计的方法
export async function calcTotalPrice(data: any, oldPriceKey = 'discountPrice', numKey = 'count', priceKey = "discountPrice") {
    const { user } = useStore();
    const { oldAge } = await user.get()

    let _data = JSON.parse(JSON.stringify(data))
    _data = _data?.sort(sortBy(oldAge ? oldPriceKey : priceKey, false))

    return _data?.reduce((prev: any, curr: any, index: number) => {
        const _price = oldAge && index < 2 ? oldPriceKey : priceKey
        console.info("curr[numKey]", curr[_price])
        return prev + (curr[numKey] * parseFloat(curr[_price]));
    }, 0);
}

// 排序方法
function sortBy(attr: any, rev?: any) {
    //第二个参数没有传递 默认升序排列
    if (rev == undefined) {
        rev = 1;
    } else {
        rev = (rev) ? 1 : -1;
    }

    return function (a: any, b: any) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
            return rev * -1;
        }
        if (a > b) {
            return rev * 1;
        }
        return 0;
    }
}

// 手机号隐藏中间的方法
export function privacyPhone(phone: string) {
    if (!phone) return "-";
    return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}

// 计算选中面积或者体积
export function getTotalArea(data: any, key = 'area', type = 'brand') {
    const newArr = data.map((item: any) => item[key])

    let total = newArr?.reduce((prev: any, curr: any, index: number) => {
        return parseFloat(prev) + parseFloat(curr);
    }, 0);

    return total.toFixed(3)
}

// 获取片数
export function getTotalPieceNum(data: any, type = 'brand') {
    let num = 0

    data.forEach((item: any) => {
        // item.turns.forEach((cItem: any) => {
        if (item._pieceNum) {
            num = num + item._pieceNum
        }
        // })
    });

    return num
}

/** *
 * 检查微信更新
 * @parmas backFn 回调函数
 */
export function getWeChatUpdate(showPrompt = false) {
    //#ifdef MP-WEIXIN
    const updateManager = uni.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
        console.info("res", res)
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
            updateManager.onUpdateReady(function (res) {
                uni.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，是否重启应用？',
                    success(res) {
                        if (res.confirm) {
                            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                            updateManager.applyUpdate()
                        }
                    },
                })
            })

            updateManager.onUpdateFailed(function (res) {
                // 新的版本下载失败
                uni.showModal({
                    title: '已经有新版本了哟~',
                    content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
                })
            })
        } else {
            if (showPrompt) {
                uni.showToast({
                    title: '已经是最新版本了！',
                    icon: 'none',
                    mask: true
                })
            }
        }
    })
    //#endif
}

// 密钥对生成 http://web.chacuo.net/netrsakeypair

// 加密
export function encrypt(txt: any) {
    const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n' +
        '2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ=='

    const encryptor = new JSEncrypt()
    encryptor.setPublicKey(publicKey) // 设置公钥
    return encryptor.encrypt(txt) // 对需要加密的数据进行加密
}

